export interface TypewriterOptions {
  el: HTMLElement | null;
  text: string;
  speed?: number;
  onFinished?: () => void;
  cursorClass?: string; // 可选：自定义光标类名
  removeCursorAfterFinish?: boolean; // 是否打完后删除光标
}

export function typewriter({
  el,
  text,
  speed = 100,
  onFinished,
  cursorClass = 'typewriter-cursor',
  removeCursorAfterFinish = true,
}: TypewriterOptions): void {
  if (!el) return;

  // 清空内容
  el.innerHTML = '';

  // 创建 span 容器用于文本显示
  const textSpan = document.createElement('span');
  el.appendChild(textSpan);

  // 创建 cursor 光标

  const cursor = document.createElement('span');
  cursor.className = cursorClass;
  cursor.textContent = '|';
  el.appendChild(cursor);

  let i = 0;

  const type = () => {
    if (i < text.length) {
      textSpan.textContent += text.charAt(i);
      i++;
      setTimeout(type, speed);
    } else {
      if (removeCursorAfterFinish) {
        cursor.remove(); // ✅ 删除光标
      }
      if (typeof onFinished === 'function') {
        onFinished();
      }
    }
  };

  type();
}
